<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import SIdentify from '@/components/Sidentify.vue'
const loginData = ref({
  username: '',
  password: ''
})
const userType = ref('学生登录')
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

let sidentifyMode = ref('') //输入框验证码
let identifyCode = ref('') //图形验证码
let identifyCodes = ref('abcdefjhijklinopqrsduvwxyz') //验证码出现的数字和字母
//组件挂载
onMounted(() => {
  identifyCode.value = ''
  makeCode(identifyCodes.value, 4)
})
// 生成随机数
const randomNum = (min, max) => {
  max = max + 1
  return Math.floor(Math.random() * (max - min) + min)
}
// 随机生成验证码字符串
const makeCode = (o, l) => {
  for (let i = 0; i < l; i++) {
    identifyCode.value += o[randomNum(0, o.length - 1)]
  }
}
// 更新验证码
const refreshCode = () => {
  identifyCode.value = ''
  makeCode(identifyCodes.value, 4)
}

import { studentLoginService, teacherLoginService, adminLoginService } from '@/api/user.js';
import { useRouter } from 'vue-router';
import { useTokenStore } from '@/stores/token.js';
import { useStore } from './Admin/store';

const router = useRouter()
const store = useStore()
const tokenStore = useTokenStore();
const login = async () => {
  if (!sidentifyMode.value) {
      ElMessage({ type: 'error', message: '验证码不能为空！' });
  }
  //验证验证码是否正确
  if (sidentifyMode.value != identifyCode.value) {
      ElMessage({ type: 'error', message: '验证码错误' });
      refreshCode();
  } else {
  let result
  try {
    if (userType.value === '学生登录') {
      result = await studentLoginService(loginData.value);
    } else if (userType.value === '教师登录') {
      result = await teacherLoginService(loginData.value);
    } else {
      result = await adminLoginService(loginData.value);
    }
  } catch (error) {
    ElMessage({ type: 'error', message: '用户名或密码错误' });
  }
  //result = await adminLoginService(loginData.value);
  console.log(result, 'result')
  if (result.code === 200) {
    //alert(result.msg ? result.msg : '成功')
    if (userType.value === '学生登录') {
      ElMessage({ type: 'success', message: '学生登录成功' });
      tokenStore.setToken(result.data);
      router.push('/studentHome');
    } else if (userType.value === '教师登录') {
      ElMessage({ type: 'success', message: '教师登录成功' });
      tokenStore.setToken(result.data);
      router.push('/teacherHome');
    } else {
      ElMessage({ type: 'success', message: '管理员登录成功' });
      tokenStore.setToken(result.data);
      store.setToken(result.data);
      router.push('/adminView');
    }
  } else {
    ElMessage({ type: 'error', message: '用户名或密码错误' });
    refreshCode();
  }
  }
}
</script>

<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="10" :offset="1" class="form">
      <el-form ref="form" size="large" autocomplete="off" :model="loginData" :rules="rules" @keyup.enter.native="login">
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-radio-group v-model="userType" size="large">
          <el-radio-button label="学生登录" />
          <el-radio-button label="教师登录" />
          <el-radio-button label="管理员登录" />
        </el-radio-group>
        <hr />
        <el-form-item prop="username">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="loginData.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"
            v-model="loginData.password"></el-input>
        </el-form-item>
        <el-form-item label="验证码">
          <el-input placeholder="请输入验证码" v-model="sidentifyMode" clearable></el-input>
        </el-form-item>
        <!-- 使用验证码组件 -->
        <div class="code" @click="refreshCode">
          <SIdentify :identifyCode="identifyCode"></SIdentify>
        </div>
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="login"
            @keyup.enter="login">登录</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
/* 样式 */
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    background: //url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
      url('@/assets/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }

    .code {
      text-align: center;
      margin-bottom: 10px;
    }

  }
}

.demo-tabs>.el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>